package com.tepth.remote.control.base.xml;

import android.os.Environment;
import android.util.Xml;

import com.tepth.remote.control.base.bean.ElementBean;
import com.tepth.remote.core.utils.file.FileUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/24
 */
public class XmlHandler {

    private static final class Hold {
        static final XmlHandler INSTANCE = new XmlHandler();
    }

    public static XmlHandler getInstance() {
        return Hold.INSTANCE;
    }

    /**
     * 写入XML文件
     *
     * @param elementBeans 要写入的集合
     * @param fenceId      围栏ID
     */
    public void writeXml(ArrayList<ElementBean> elementBeans, String fenceId) throws Exception {
        XmlSerializer serializer = Xml.newSerializer();
        File file = FileUtil.createXml(fenceId);
        OutputStream outputStream = new FileOutputStream(file);
        serializer.setOutput(outputStream, "utf-8");
        serializer.startDocument("utf-8", true);
        serializer.startTag(null, "eleInfos");
        for (ElementBean element : elementBeans) {
            serializer.startTag(null, "eleInfo");
            // 围栏ID
            serializer.startTag(null, "Eleid");
            serializer.text(element.getId() + "");
            serializer.endTag(null, "Eleid");
            // 编号
            serializer.startTag(null, "Sort");
            serializer.text(element.getSort());
            serializer.endTag(null, "Sort");
            // 用户ID
            serializer.startTag(null, "Uid");
            serializer.text(String.valueOf(element.getUserId()));
            serializer.endTag(null, "Uid");
            // Radius
            serializer.startTag(null, "Radius");
            serializer.text(String.valueOf(element.getRadius()));
            serializer.endTag(null, "Radius");
            // 纬度
            serializer.startTag(null, "Lat");
            serializer.text(String.valueOf(element.getLatitude()));
            serializer.endTag(null, "Lat");
            // 经度
            serializer.startTag(null, "Lng");
            serializer.text(String.valueOf(element.getLongitude()));
            serializer.endTag(null, "Lng");
            //END
            serializer.endTag(null, "eleInfo");
        }
        serializer.endTag(null, "eleInfos");
        serializer.endDocument();
        outputStream.close();
    }

    /**
     * 解析XML
     *
     * @param fenceId 要解析的XML名字
     * @return ElementBean集合
     */
    public ArrayList<ElementBean> readXml(String fenceId) throws Exception {
        ArrayList<ElementBean> elementBeans = new ArrayList<>();
        final String xmlUrl = Environment.getExternalStorageDirectory()
                .getAbsoluteFile() + "/" + "tepth" + "/" + fenceId + ".xml";
        final File dir = new File(xmlUrl);
        if (!dir.exists()) {
            return elementBeans;
        }
        final InputStream inputStream = new FileInputStream(dir);
        final XmlPullParser pullParse = Xml.newPullParser();
        // 为pull解器设置要解析的
        pullParse.setInput(inputStream, "UTF-8");
        int event = pullParse.getEventType();
        ElementBean bean = null;
        while (event != XmlPullParser.END_DOCUMENT) {
            switch (event) {
                case XmlPullParser.START_DOCUMENT:
                    elementBeans = new ArrayList<>();
                    break;
                case XmlPullParser.START_TAG:
                    // 判断开始标签元素是否是
                    if ("eleInfo".equals(pullParse.getName())) {
                        bean = new ElementBean();
                    }
                    if (bean != null) {
                        // 判断开始标签元素是否是id
                        if ("Eleid".equals(pullParse.getName())) {
                            bean.setId(pullParse.nextText());
                            // 判断开始标签元素是否是Sort
                        } else if ("Sort".equals(pullParse.getName())) {
                            bean.setSort(pullParse.nextText());
                            // 判断开始标签元素是否是Uid
                        } else if ("Uid".equals(pullParse.getName())) {
                            bean.setUserId(Integer.parseInt(pullParse
                                    .nextText()));
                            // 判断开始标签元素是否是Radius
                        } else if ("Radius".equals(pullParse.getName())) {
                            bean.setRadius(Integer.parseInt(pullParse.nextText()));
                            // 判断开始标签元素是否是latitude
                        } else if ("Lat".equals(pullParse.getName())) {
                            bean.setLatitude(Double.parseDouble(pullParse
                                    .nextText()));
                            // 判断开始标签元素是否是longitude
                        } else if ("Lng".equals(pullParse.getName())) {
                            bean.setLongitude(Double.parseDouble(pullParse
                                    .nextText()));
                        }
                    }
                    break;
                // 判断当前事件是否是标签元素结束事件
                case XmlPullParser.END_TAG:
                    // 判断结束标签元素是否是eleInfo
                    if ("eleInfo".equals(pullParse.getName())) {
                        elementBeans.add(bean);
                    }
                    break;
                default:
                    break;
            }
            // 进入下一个元素并触发相应事件
            event = pullParse.next();
        }
        inputStream.close();
        return elementBeans;
    }
}
